from rest_framework import serializers
from .models import Banner,Notice,Collection,Area
from libs.baidu_ai import BaiDuFace
from rest_framework.exceptions import APIException

# 轮播图表序列化类
class BannerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Banner
        fields = '__all__'

# 社区通知序列化类
class NoticeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Notice
        fields = ['id','title']

#采集序列化
class CollectionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Collection
        fields = ['id', 'name', 'avatar', 'area']
        depth = 1  # area 外键关联详情拿到

class CollectionSaveSerializer(serializers.ModelSerializer):  # 新增序列化类
    class Meta:
        model = Collection
        fields = ['name', 'avatar', 'area']


    def create(self, validated_data):
        # 上传到百度人脸
        ai=BaiDuFace()
        #取出人脸图片
        file_obj = validated_data.get('avatar')
        #取出人名,转化为拼音
        name = validated_data.get('name')
        name_pinyin = ai.name_to_pinyin(name)

        #上传百度人脸
        res = ai.add_user(file_obj,name_pinyin)
        if res.get('error_code')==0:
        # 完成保存
            validated_data['face_token'] = res.get('result').get('face_token')
            validated_data['name_pinyin'] = name_pinyin
            instance = super().create(validated_data) #保存数据库
            return instance
        else:
            raise APIException('采集失败')
# 网格过滤
class AreaSerializer(serializers.ModelSerializer):
        class Meta:
            model = Area
            fields = ['id', 'name', 'desc']


class StatisticsListSerializer(serializers.Serializer):
    date=serializers.DateTimeField(format='%Y年%m月%d日')
    count = serializers.IntegerField()

